package com.guisu.material.recyclerview.custom

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.guisu.material.R
import com.guisu.material.databinding.ActivityTestBinding

class TestActivity: AppCompatActivity() {

    private lateinit var binding: ActivityTestBinding
    private val TAG = javaClass.simpleName
    private val count = 5000000

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityTestBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.table.setAdapter(MyAdapter(this))
    }

    inner class MyAdapter(context: Context): RecyclerView.Adapter{
        private val inflater: LayoutInflater
        private var height: Int = 80

        init {
            inflater = LayoutInflater.from(context)
        }

        override fun onCreateViewHolder(
            position: Int,
            convertView: View?,
            parent: ViewGroup?
        ): View {
            if (convertView == null) {
                return when (getItemViewType(position)) {
                    0 -> {
                        val view = inflater.inflate(R.layout.item_custom_text, parent, false)
                        view.post {
                            height = view.height
                        }
                        view
                    }
                    else -> {
                        val view = inflater.inflate(R.layout.item_custom_img, parent, false)
                        view.post {
                            height = view.height
                        }
                        view
                    }
                }
            }
            return convertView
        }

        override fun onBindViewHolder(
            position: Int,
            convertView: View,
            parent: ViewGroup?
        ): View {
            val textView = convertView.findViewById<TextView>(R.id.tv1)
            if (textView != null) {
                textView.text = "第 $position 行"
            }
            return convertView
        }

        override fun getItemCount(): Int {
            return count
        }

        override fun getItemViewType(row: Int): Int {
            if (row % 2 == 0) {
                return 1
            }
            return 0
        }

        override fun getViewTypeCount(): Int {
            return 2
        }

        override fun getHeight(index: Int): Int {
            return height
        }
    }
}